package com.pollyduan.springInitializr;

import java.io.File;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.io.ClassPathResource;

import io.spring.initializr.metadata.DependenciesCapability;
import io.spring.initializr.metadata.DependencyGroup;
import io.spring.initializr.metadata.InitializrMetadata;
import io.spring.initializr.metadata.InitializrMetadataProvider;

@SpringBootApplication
public class SpringInitializrApplication implements CommandLineRunner {

	public static void main(String[] args) {
		//初始化metadata
		File file = new File("/tmp/spring-boot");
		if (!file.exists()) {
			file.getParentFile().mkdirs();
			ClassPathResource resource = new ClassPathResource("project_metadata/spring-boot");
			System.out.println("prepare metadata starting...");
			if(!resource.exists()) {
				//马上拉一次远端数据
				System.out.println("internal resource no found, fetch from remote just now.");
				new MetadataPullThread().fetch();
			}else {
				try {
					InputStream in = resource.getInputStream();
					Files.copy(in, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		new MetadataPullThread().start();
		try {
			Thread.sleep(3 * 1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		if(file.exists()) {
			System.out.println("prepare metadata ok.");
		}

		//启动web
		SpringApplication.run(SpringInitializrApplication.class, args);
	}

	@Autowired
	public InitializrMetadataProvider dependencyMetadataProvider;
	@Autowired
	private ThirdPartyDependenciesConfiguration thirdPartyDependenciesConfiguration;

	@Override
	public void run(String... args) throws Exception {
		InitializrMetadata metadata = dependencyMetadataProvider.get();
		DependenciesCapability dependenciesCapability = metadata.getDependencies();
		List<DependencyGroup> listDepencyGroup = dependenciesCapability.getContent();
		listDepencyGroup.add(thirdPartyDependenciesConfiguration.getDependencies());
	}
}
